#!/bin/bash
export TERM=xterm
#
# Usage:
# screen -dmS autouam &&
# screen -x -S autouam -p 0 -X stuff "bash /root/autouam.sh" &&
# screen -x -S autouam -p 0 -X stuff $'\n'
#

mode="load"
# 两种模式可选，一：cpu 二：load

challenge="1"
# 是否同时开启验证码质询 设为 1 即开启

keeptime="900"
# ≈开盾最小时间，如 60 则开盾 60 秒内负载降低不会关，60 秒后关

interval="1"
# 检测间隔时间，默认 0.5 秒

email="203999@qq.com"
# CloudFlare 账号邮箱

api_key="eK-qaOsA4ooYMpPhQpCcmmwXmjDBko8XacBjsoyU"
# CloudFlare API KEY

zone_id="fabdeca4e6f947479bec9b47f9497f99"
# 区域 ID 在域名的概述页面获取

default_security_level="high"
# 默认安全等级 关闭 UAM 时将会把安全等级调整为它

api_url="https://api.cloudflare.com/client/v4/zones/$zone_id/settings/security_level"
# API 的地址

api_url1="https://api.cloudflare.com/client/v4/zones/$zone_id/firewall/rules"
# API 的地址之二

api_url2="https://api.cloudflare.com/client/v4/zones/$zone_id/filters"
# API 的地址之三

auto="0"

uaf="OFF"

waf="OFF"

# 安装依赖
if [ ! $(which jq 2> /dev/null) ]; then
	echo "jq not found!"
	if [ -f "/usr/bin/yum" ] && [ -d "/etc/yum.repos.d" ]; then
		yum install jq -y
	elif [ -f "/usr/bin/apt-get" ] && [ -f "/usr/bin/dpkg" ]; then
		apt-get install jq -y
	fi
fi

formatTime() {
    local seconds=$1

    # 定义时间单位
    local units=('天' '小时' '分钟' '秒')

    # 定义时间间隔
    local durations=(86400 3600 60 1)

    local result=""

    for ((i=0; i<${#units[@]}; i++)); do
        if ((seconds >= durations[i])); then
            local count=$((seconds / durations[i]))
            result+="${count}${units[i]}"
            seconds=$((seconds % durations[i]))
        fi
    done

    echo "$result"
}

for((;;))
do
if [ "$mode" = "cpu" ]; then
	check=60   #5 秒内 CPU 连续超过 60 则开启 UAM【可以根据您的服务器负荷情况调整】
	#系统空闲时间
	TIME_INTERVAL=3
	time=$(date "+%Y-%m-%d %H:%M:%S")
	LAST_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
	LAST_SYS_IDLE=$(echo $LAST_CPU_INFO | awk '{print $4}')
	LAST_TOTAL_CPU_T=$(echo $LAST_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
	sleep $TIME_INTERVAL
	NEXT_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
	NEXT_SYS_IDLE=$(echo $NEXT_CPU_INFO | awk '{print $4}')
	NEXT_TOTAL_CPU_T=$(echo $NEXT_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')

	#系统空闲时间
	SYSTEM_IDLE=`echo $NEXT_SYS_IDLE $LAST_SYS_IDLE | awk '{print $1-$2}'`
	#CPU 总时间
	TOTAL_TIME=`echo $NEXT_TOTAL_CPU_T $LAST_TOTAL_CPU_T | awk '{print $1-$2}'`
	load=`echo $SYSTEM_IDLE $TOTAL_TIME | awk '{printf "%.2f", 100-$1/$2*100}'`
else
	load=$(awk '{print int($1)}' /proc/loadavg)
	check=$(cat /proc/cpuinfo | grep "processor" | wc -l)
	check=$((check - 2))
fi

if [ ! -f "/home/centos/status.txt" ];then
	echo "" > /home/centos/status.txt
else
	status=$(cat /home/centos/status.txt)
fi
if [ -f "/home/centos/ruleid.txt" ]; then
	ruleid=$(cat /home/centos/ruleid.txt)
fi
if [ -f "/home/centos/filterid.txt" ]; then
	filterid=$(cat /home/centos/filterid.txt)
fi
now=$(date +%s)
time=$(date +%s -r /home/centos/status.txt)

ts=$(date +"%Y-%m-%d %H:%M:%S")

#if [[ $status -eq 1 ]]; then
#	echo "[$ts]当前[$mode]负载 $load, WAF状态: ON"
#	FILE="/home/centos/status.txt"
#	if find "/home/centos/status.txt" -mmin +30 | grep -q 'status.txt'; then
#	  	if [[ "$challenge" -eq 1 ]]; then
#    	  echo -e "[$ts] $mode 负载高于$check，开启 WAF"
#    		/home/centos/waf --mod=on
#        echo "a0634671f23d4767b5ddcc9679b55646" > ruleid.txt
#        echo 1 > /home/centos/status.txt
#    		sleep 3s
#    		kill -USR2  $(cat /www/server/php/73/var/run/php-fpm.pid)
#    		rm -rf /www/wwwroot/iggm/runtime/*
#    	fi
#	fi
#else
#  echo "[$ts]当前[$mode]负载 $load WAF状态: OFF"
#fi

echo "[$ts]当前[$mode]负载 $load, 低于 $check , WAF: OFF"

newtime=`expr $now - $time`
closetime=`expr $keeptime - $newtime`

if [[ $load > $check ]]; then
	if [[ "$challenge" -eq 1 && -z "$status" ]]; then
	  echo -e "[$ts] $mode $load 高于 $check 开启 WAF"
#		/home/centos/waf --mod=on
    echo "a0634671f23d4767b5ddcc9679b55646" > ruleid.txt
    echo 1 > /home/centos/status.txt
		sleep 3s
		kill -USR2  $(cat /www/server/php/73/var/run/php-fpm.pid)
		rm -rf /www/wwwroot/iggm/runtime/*
	else
		echo -e "[$ts]$mode $load 负载低于 $check 不处理"
	fi
fi

sleep $interval
#clear
done

